<template>
  <div class="jkhaled-login">
    <Card style="width:100%;height: auto;" :bordered="false" :shadow="false" :dis-hover="true">
      <div style="text-align:left">
        <div slot="title">
          <img :src="logo" style="max-width:390px; height: auto;">
        </div>
        <hr style="background: rgba(120,120,225,0.4);margin-bottom: 20px;" />
        <Form ref="loginValidate" :rules="loginValidate" :model="loginForm" :label-width="50">
          <Form-item label="账号" prop="userName">
            <Input v-model="loginForm.userName" placeholder="用户名/邮箱/手机号"></Input>
          </Form-item>
          <Form-item label="密码" prop="password">
            <Input v-model="loginForm.password" type="password" placeholder="密码"></Input>
          </Form-item>
          <Form-item>
            <Button type="ghost" shape="circle" @click="login('loginValidate')" style="margin-left: 58px">提交</Button>
            <Button type="ghost" shape="circle" @click="reset('loginValidate')" style="margin-left: 8px">重置</Button>
          </Form-item>
        </Form>
      </div>
    </Card>
  </div>
</template>

<script>
	import { mapState, mapMutations } from 'vuex'
  import userApi from '@/api/userApi'

  export default {
    name: 'login',
    data() {
      return {
        logo: require('@/assets/JKhaled.jpg'),
        msg: 'Welcome to Your Vue.js App',
        loginForm: {
          userName: '',
          password: ''
        },
        loginValidate: {
          userName: [{
            required: true,
            message: '用户名不能为空',
            trigger: 'blur'
          }],
          password: [{
            required: true,
            message: '密码不能为空',
            trigger: 'blur'
          }]
        }
      }
    },
    methods: {
      ...mapMutations([
        'updateMe'
      ]),
      login(name) {
        this.$refs[name].validate((valid) => {
          if(valid) {
            var msg = this.$Message.loading({
              content: '正在登录中...',
              duration: 0
            })
            userApi.login(this.loginForm).then(data => {
              sessionStorage.setItem('token', data.token)
              // 获取当前用户信息
              userApi.me().then(data => {
                this.updateMe(data)
              }).catch(errMsg => {
                this.$Message.error(errMsg)
              })

              this.$Message.destroy()
              this.$router.push('/')
            }).catch(errMsg => {
              this.$Message.destroy()
              this.$Message.error(errMsg)
            })
          } else {
            this.$Message.error('请认真填写表单!');
          }
        })
      },
      reset(name) {
        this.$refs[name].resetFields();
      }
    }
  }
</script>

<style scoped>
  .jkhaled-login {
    width: 420px;
    height: 600px;
    border: solid 1px rgba(120, 120, 225, 0.4);
    margin: 0px auto;
    margin-top: 60px;
  }
</style>